package script

import (
	"game/core"
	"game/core/tools"
	_ "image/png"

	"github.com/hajimehoshi/ebiten/v2"
	"github.com/solarlune/resolv"
)

type Enemy struct {
	core.Sprite
	ProjectileMovement *core.ProjectileMovement
	Animation          *core.Animation
}

func NewEnemy(position resolv.Vector, movement core.ProjectileMovementOption) *Enemy {

	enemy := &Enemy{
		Sprite: core.Sprite{
			Position: &resolv.Vector{X: 0, Y: 0},
			Scale:    &resolv.Vector{X: 0.5, Y: 0.5},
			Image:    EnemyImg,
		},
	}
	//
	enemy.ProjectileMovement = core.NewProjectileMovement(enemy, movement)
	enemy.SetPosition(position)
	//
	wh := enemy.GetWH()
	enemy.Collision = resolv.NewRectangle(enemy.GetCenter().X, enemy.GetCenter().Y, wh.X, wh.Y)
	enemy.Collision.SetData(enemy)

	enemy.NewTimer().StartTimer(1, func() {
		e := enemy.GetCenter()
		r := tools.MRand(0, 2)
		if r == 0 {
			AddNode(GG, core.LayerEnemyBullet, NewEnemyBullet(e))
		}
	}, true)

	return enemy
}

var r float64 = 0

func (p *Enemy) Update(dt float64) error {

	p.ProjectileMovement.Update(dt)

	p.Collision.IntersectionTest(resolv.IntersectionTestSettings{
		TestAgainst: p.Collision.SelectTouchingCells(1).FilterShapes(),
		OnIntersect: func(set resolv.IntersectionSet) bool {
			// if set.OtherShape.Tags().Has(core.TagWall) {
			// 	p.MoveVec(set.MTV)
			// }
			if set.OtherShape.Tags().Has(core.TagPlayerBullet) {
				positon := p.GetCenter()
				AddNode(GG, core.LayerEnemyBullet, NewBoom(positon))

				p.Destory()
			}
			//fmt.Println(set.OtherShape.Tags().Has(core.TagPlayerBullet))
			return true
		},
	})
	//fmt.Println(p.Collision.Center().X, p.Collision.Center().Y)
	return nil
}

func (p *Enemy) Draw(screen *ebiten.Image) {
	op := &ebiten.DrawImageOptions{}

	op.GeoM.Scale(p.Sprite.Scale.X, p.Sprite.Scale.Y)
	op.GeoM.Translate(p.Position.X, p.Position.Y)

	screen.DrawImage(p.Image, op)
}
